<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label">状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="">
                                            <option value="">请选择状态</option>
                                            <option value="inStock">入库中</option>
                                            <option value="created">待签收</option>
                                            <option value="isSign">已签收</option>
                                            <option value="isStock">已入库</option>
                                            <option value="inSign">签收中</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">采购单编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入入库单编号"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit>查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="addPurchaseOrderBtn" class="layui-btn icon-btn color-reseda">添加采购订单</button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="purchaseTable" lay-filter="purchaseTable"></table>
        </div>
    </div>
</div>


<style>
    .addPurchaseOrder label {
        width: 85px;
        padding: 10px 10px 10px 0px;
    }

    .addPurchaseOrder .layui-table-cell, .addPurchaseCommodity .layui-table-cell, .purchaseTableDetails .layui-table-cell {
        height: auto;
        max-height: 80px;
    }

    .layui-table-cell img {
        height: auto;
        width: auto;
        max-height: 80px;
    }
</style>

<!-- 表格操作列 -->
<script type="text/html" id="purchaseTableBar">
    <!--    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>-->
    <!--    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
    <a class="layui-btn layui-btn-xs" lay-event="details">查看详情</a>
    <a class="layui-btn layui-btn-xs" lay-event="print">打印采购单</a>
</script>

<!--purchaseTableDetails-->
<!--详情-->
<script type="text/html" id="purchaseTableDetails">
    <form class="layui-form model-form purchaseTableDetails"
          style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box" style="height: calc(100% - 75px);">
            <div class="layui-card">
                <div class="layui-card-body">
                    <!-- 头部操作栏 -->
                    <div class="toolbar">
                        <!-- 表格 -->
                        <div class="layui-row table-bor">
                            <table class="layui-table" id="purchaseTableDetailsTable"
                                   lay-filter="purchaseTableDetailsTable"></table>
                        </div>
                        <br>
                        <table class="layui-table" id="purchaseTableDetailsTableList"
                               lay-filter="purchaseTableDetailsTableList"></table>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>


<!--addPurchaseOrder-->
<!-- 添加采购订单 -->
<script type="text/html" id="addPurchaseOrder">
    <div class="layui-fluid addPurchaseOrder">
        <form lay-filter="storageWorkAddForm" class="layui-form model-form"
              style="padding: 5px 20px 0;height: calc(100% - 5px);overflow: hidden;">
            <div class="open-details-box" style="height: calc(100% - 55px);">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">采购类型</label>
                        <div class="layui-input-inline">
                            <select name="purchaseTypeId" id="purchaseTypeId" lay-verify="required"
                                    lay-filter="purchaseTypeId"></select>
                        </div>
                        <input type="hidden" name="purchaseTypeName" id="purchaseType">
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">紧急程度</label>
                        <div class="layui-input-inline">
                            <select name="purchaseDegreeId" id="purchaseDegreeId" lay-verify="required"
                                    lay-filter="purchaseDegreeId"></select>
                        </div>
                        <input type="hidden" name="purchaseDegreeName" id="purchaseDegree">
                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">供应商</label>
                        <div class="layui-input-inline">
                            <select name="supplierId" lay-verify="" lay-filter="supplierId" id="supplierId">
                                <option value="">请选择供应商</option>
                            </select>
                            <input type="hidden" name="supplier" id="supplier">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">供应商联系人</label>
                        <div class="layui-input-inline">
                            <input type="text" name="supplierName" class="layui-input" placeholder="供应商联系人"
                                   id="supplierName" readonly>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">采购部门</label>
                        <div class="layui-input-inline">
                            <select name="department" id="department" lay-verify="required">
                                <option value="1">采购部</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">采购申请人</label>
                        <div class="layui-input-inline">
                            <input type="text" name="creatorName" lay-verify="required" class="layui-input" readonly
                                   id="creatorName">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">订单审核人</label>
                        <div class="layui-input-inline">
                            <select name="orderAuditorId" id="orderAuditorId" lay-verify="required"
                                    lay-filter="orderAuditorId"></select>
                        </div>
                        <input type="hidden" name="orderAuditor" id="orderAuditor">
                    </div>
                </div>
                <div class="layui-form-item">
                    <a class="layui-btn" style="float: left; margin-left: 20px;" id="addPurchaseCommodityBtn">添加采购商品</a>
                </div>
                <!-- 表格 -->
                <table class="layui-table" id="addPurchaseOrderTable" lay-filter="addPurchaseOrderTable"></table>
            </div>
            <div class="layui-form-item text-right">
                <a class="layui-btn" lay-filter="addPurchaseOrderSubmit" lay-submit>提交</a>
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            </div>
        </form>
    </div>
</script>

<!--addPurchaseCommodity-->
<!-- 添加采购商品 -->
<script type="text/html" id="addPurchaseCommodity">
    <form lay-filter="addPurchaseCommodityForm" class="layui-form model-form addPurchaseCommodity"
          style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box" style="height: calc(100% - 75px);">
            <div class="layui-row">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" name="skuCode" placeholder="请输入物料编号">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <a class="layui-btn icon-btn" lay-filter="" lay-submit type="buuton">搜索</a>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="addPurchaseCommodityTable"
                   lay-filter="addPurchaseOrderTable"></table>
        </div>
        <div class="layui-form-item text-right">
            <a class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</a>
            <a class="layui-btn" id="addPurchaseCommoditySubmit">提交</a>
        </div>
    </form>
</script>

<!--addPurchaseCommodityBar-->
<!-- 添加采购商品操作 -->
<script type="text/html" id="addPurchaseCommodityBar">
    <a class="layui-btn layui-btn-xs" lay-event="addPurchaseCommodityDetails">详情</a>
</script>


<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;

        form.render('select');

        // 渲染表格
        var insTb = table.render({
            elem: '#purchaseTable',
            url: config.base + 'enterprisecab/order/admin/purchase/getPurchaseList',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'}
                , {field: 'code', sort: true, title: '采购单编号'}
                , {field: 'stockTypeDesc', title: '入库类型'}
                , {field: 'skuNum', title: '入库数'}
                , {field: 'supplier',  title: '供应商'}
                , {field: 'orderMoney', title: '订单金额'}
                , {field: 'statusDesc', title: '状态'}
                , {field: 'orderAuditor',  title: '审核人'}
                , {field: 'createTime', title: '入库时间'}
                , {align: 'left', toolbar: '#purchaseTableBar', title: '操作'}
            ]],
            done: function (res, curr, count) {
            }
        });

        // 工具条点击事件
        table.on('tool(purchaseTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'details') {
                showPurchaseTableDetails(data)
            }
        });

        //监听排序
        table.on('sort(purchaseTable)', function (obj) {
            table.reload('purchaseTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', data => {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#addPurchaseOrderBtn').click(function () {
            showAddPurchaseOrder();
        });

        //显示详情弹窗
        function showPurchaseTableDetails(data) {
            admin.open({
                type: 1,
                area: ['82%', '850px'],
                offset: '65px',
                title: '查看生产入库任务详情',
                content: $('#purchaseTableDetails').html(),
                success: function () {
                    let purchaseTableDetailsTb = table.render({
                        elem: '#purchaseTableDetailsTable',
                        data: [data],
                        page: false,
                        cellMinWidth: 100,
                        cols: [[
                            {field: 'code', title: '采购单编号'}
                            , {field: 'purchaseTypeName', title: '采购类型'}
                            , {field: 'purchaseDegreeName', title: '紧急程度'}
                            , {field: 'supplier', title: '供应商'}
                            , {field: 'supplierName', title: '供应商联系人'}
                            , {field: 'department', title: '采购部门'}
                            , {field: 'creatorName', title: '采购申请人'}
                            , {field: 'orderAuditor', title: '订单审核人'}
                        ]]
                    });

                    let purchaseTableDetailsTbList = table.render({
                        elem: '#purchaseTableDetailsTableList',
                        data: data.purchaseDetailList,
                        page: true,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {field: 'skuPic', title: '物料图片', templet: d => '<img src="' + d.skuPic + '"/>'}
                            ,  {field: 'skuCode', title: '物料编号'}
                            , {field: 'skuSpec', title: '规格号'}
                            , {field: 'productType', title: '物料类型'}
                            , {field: 'marketPrice', title: '物料单价'}
                            , {field: 'unitName', title: '计价单位'}
                            , {field: 'num', title: '采购数量'}
                            , {field: 'amount', title: '小计金额'}
                        ]]
                    });
                }
            });
        }

        let showAddPurchaseOrderData = [];

        // 显示添加采购订单弹窗
        function showAddPurchaseOrder(data) {
            admin.open({
                type: 1,
                area: ['1400px', '800px'],
                offset: '65px',
                title: '添加生产入库计划',
                content: $('#addPurchaseOrder').html(),
                success: function () {
                    form.render("select");
                    showAddPurchaseOrderData = [];

                    admin.req('enterprisecab/order/admin/purchase/getSupplier', {}, res => {
                        if (res.code === 200) {
                            loadSelectHtml(res.data, '请选择供应商', 'supplierId', 2);
                        }
                    }, 'GET');
                    form.on('select(supplierId)', d => {
                        $('#supplierName').val($("#supplierId option:checked").attr("administratorName"));
                        $('#supplier').val($("#supplierId option:checked").text());
                    });

                    admin.req('enterprisecab/order/admin/purchase/getOrderAuditor', {}, res => {
                        if (res.code === 200) {
                            loadSelectHtml(res.data, '请选择订单审核人', 'orderAuditorId', 1);
                        }
                    }, 'GET');


                    form.on('select(orderAuditorId)', d => {
                        $('#orderAuditor').val($("#orderAuditorId option:checked").text());
                    });

                    //采购类型
                    admin.req('enterprisecab/order/admin/purchaseType/list', {}, res => {
                        if (res.code === 200) {
                            loadSelectHtml(res.data, '请选择采购类型', 'purchaseTypeId', 3);
                        }
                    }, 'GET');

                    form.on('select(purchaseTypeId)', d => {
                        $('#purchaseType').val($("#purchaseTypeId option:checked").text());
                    });

                    //紧急程度
                    admin.req('enterprisecab/order/admin/purchaseDegree/list', {}, res => {
                        if (res.code === 200) {
                            loadSelectHtml(res.data, '请选择紧急程度', 'purchaseDegreeId', 4);
                        }
                    }, 'GET');

                    form.on('select(purchaseDegreeId)', d => {
                        $('#purchaseDegree').val($("#purchaseDegreeId option:checked").text());
                    });

                    $('#creatorName').val(config.getUser().username);
                    let addPurchaseOrderTb = table.render({
                        elem: '#addPurchaseOrderTable',
                        data: showAddPurchaseOrderData,
                        limit: Number.MAX_VALUE,
                        height: 450,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {field: 'productPic', title: '物料图片', templet: d => '<img src="' + d.productPic + '"/>'}
                            ,  {field: 'skuCode', title: '物料编号'}
                            , {field: 'skuSpecValueNames', title: '规格号'}
                            , {field: 'productType', title: '物料类型'}
                            , {
                                field: 'supplyPrice',
                                title: '物料单价',
                                templet: d => '<input type="number" lay-verify="required" class="layui-input marketPrice" value="' + d.supplyPrice + '"/>'
                            }
                            , {field: 'unitName', title: '计价单位'}
                            , {
                                field: 'num',
                                title: '采购数量',
                                templet: d => '<input type="number" lay-verify="required" class="layui-input num" value="' + d.num + '"/>'
                            }
                            , {
                                field: 'amount',
                                title: '小计金额',
                                templet: d => '<span class="amount"></span>'
                            }
                        ]],
                        done: function (res, curr, count) {

                        }
                    });
                    $("body").delegate(".marketPrice", "change", function () {
                        if ($(this).val() <= 0) {
                            $(this).val(1)
                        }
                        $(this).parents('tr').find('.amount').text($(this).parents('tr').find('.num').val() * $(this).val());
                        showAddPurchaseOrderData[$(this).parents('tr').index()].marketPrice = $(this).val();
                        showAddPurchaseOrderData[$(this).parents('tr').index()].amount = $(this).parents('tr').find('.amount').text()

                    });

                    $("body").delegate(".num", "change", function () {
                        if ($(this).val() <= 0) {
                            $(this).val(showAddPurchaseOrderData[$(this).parents('tr').index()].inventory)
                        }

                        $(this).parents('tr').find('.amount').text($(this).parents('tr').find('.marketPrice').val() * $(this).val());

                        showAddPurchaseOrderData[$(this).parents('tr').index()].num = $(this).val();
                        showAddPurchaseOrderData[$(this).parents('tr').index()].amount = $(this).parents('tr').find('.amount').text();
                    });

                    $('#addPurchaseCommodityBtn').click(() => {
                        showAddPurchaseCommodity()
                    });

                    form.on('submit(addPurchaseOrderSubmit)', d => {
                        let amountValue = true; //是否有小计金额的值小于等于0
                        if (showAddPurchaseOrderData.length <= 0) {
                            layer.msg('请添加需要采购的商品', {icon: 5});
                            return false;
                        }

                        showAddPurchaseOrderData.some(item => {
                            item.skuSpec = item.skuSpecValueNames;
                            item.stockNumber = item.inventory;
                            item.skuPic = item.productPic;
                            if (item.amount <= 0) {
                                amountValue = false;
                                return false;
                            }
                        });
                        if (!amountValue) {
                            layer.msg('小计金额不能小于或者等于0', {icon: 5});
                            return false;
                        }

                        d.field.purchaseDetailList = showAddPurchaseOrderData;

                        layer.load(2);
                        admin.req('enterprisecab/order/admin/purchase/addPurchase', JSON.stringify(d.field), res => {
                            layer.closeAll('loading');
                            if (res.code === 200) {
                                layer.closeAll();
                                layer.msg(res.msg, {icon: 1});
                                table.reload('purchaseTable');

                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8')

                    })
                }
            });
        }


        //显示添加采购商品弹窗
        function showAddPurchaseCommodity() {
            let addPurchaseCommodityTableData = [];
            admin.reqSync('enterprisecab/order/admin/purchase/getInventoryProduct', {page: 1, limit: 99999}, res => {
                addPurchaseCommodityTableData = res.data;
            });
            let addPurchaseCommodityPopUp = admin.open({
                type: 1,
                area: ['1300px', '700px'],
                offset: '85px',
                title: '添加采购商品',
                content: $('#addPurchaseCommodity').html(),
                success: function () {
                    form.render("select");
                    let addPurchaseCommodityTb = table.render({
                        elem: '#addPurchaseCommodityTable',
                        data: addPurchaseCommodityTableData.filter((item) => !showAddPurchaseOrderData.some((ele) => ele.skuCode === item.skuCode)),
                        limit: Number.MAX_VALUE,
                        height: 450,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'checkbox'}
                            , {
                                field: 'productPic',
                                title: '物料图片',
                                templet: d => '<img src="' + d.productPic + '"/>'
                            }
                            , {field: 'skuCode',title: '物料编号'}
                            , {field: 'skuSpecValueNames', title: '规格号'}
                            , {field: 'productType', title: '物料类型'}
                            , {field: 'supplyPrice', title: '物料单价'}
                            , {field: 'unitName', title: '计价单位'}
                            , {field: 'inventory', title: '库存数量'}
                            , {field: '',  title: '库存金额'}
                            , {align: 'left', toolbar: '#addPurchaseCommodityBar', title: '操作'}
                        ]]
                    });

                    $('#addPurchaseCommoditySubmit').click(() => {
                        let checkStatus = table.checkStatus('addPurchaseCommodityTable');
                        if (checkStatus.data.length > 0) {

                            let showAddPurchaseOrderDataArrays = [...showAddPurchaseOrderData, ...checkStatus.data];
                            let showAddPurchaseOrderDataArraysMap = new Map();
                            for (let item of showAddPurchaseOrderDataArrays) {
                                if (!showAddPurchaseOrderDataArraysMap.has(item.skuCode)) {
                                    showAddPurchaseOrderDataArraysMap.set(item.skuCode, item)
                                }
                            }
                            showAddPurchaseOrderData = [...showAddPurchaseOrderDataArraysMap.values()];
                            showAddPurchaseOrderData.forEach(item => {
                                item.marketPrice = item.supplyPrice
                            });
                            layer.close(addPurchaseCommodityPopUp);
                            table.reload('addPurchaseOrderTable', {data: showAddPurchaseOrderData});
                        } else {
                            layer.msg('请选择要采购的商品', {icon: 5})
                        }

                    })
                }
            });
        }

        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '960px',
                offset: '65px',
                title: data ? '修改采购' : '添加采购',
                content: $('#purchaseForm').html(),
                success: function () {
                    if (data) {
                        var option = $("form select[name='stockType']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.stockType == item.text) {
                                data.stockType = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='type']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.type == item.text) {
                                data.type = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='exigencyLevel']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.exigencyLevel == item.text) {
                                data.exigencyLevel = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='status']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.status == item.text) {
                                data.status = item.value;
                            }
                        });
                    }

                    form.val('purchaseForm', data);
                    // 表单提交事件
                    form.on('submit(purchaseFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'order/order/admin/purchase/update' : 'order/order/admin/purchase/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('purchaseTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('order/order/admin/purchase/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#purchaseBtnExport').click(function () {
            var checkRows = table.checkStatus('purchaseTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

        /*渲染下拉框*/
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    var opDesc = data[i].username;
                    if (data[i].nickname != undefined && data[i].nickname != '') {
                        opDesc = data[i].nickname + '|' + data[i].username;
                    }
                    html += `<option value='${data[i].id}'>${opDesc}</option>`;
                } else if (type == 2) {
                    html += `<option value='${data[i].id}' administratorName='${data[i].administratorName}' >${data[i].companyName}</option>`;
                } else if (type == 3) {
                    html += `<option value='${data[i].id}' administratorName='${data[i].administratorName}' >${data[i].name}</option>`;
                } else if (type == 4) {
                    html += `<option value='${data[i].id}' administratorName='${data[i].administratorName}' >${data[i].name}</option>`;
                }

            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }
    });
</script>